<?php
class Admin_ProductController extends Apps_Controller_Action_Admin {
    public function readAction() {

        $tbProduct = new Model_DbTable_Product();
        $select = $tbProduct->getSelectGrid();

        $grid = new Grid_Product_Product('product-grid');
        $grid->setCaption('Product List');
        $grid->setSource(new OeZend_Widget_Grid_Source_ZendDbSelect($select));
        $grid->setView(new OeZend_Widget_Grid_View());
        $grid->setDisablePaginator();

        $grid->deploy();

        $this->view->grid = $grid;
    }

    public function createAction() {
        $rq = $this->_request;

        $tbProduct = new Model_DbTable_Product();
        $f 	= new Admin_Form_AddProduct();

        if ($rq->isPost()) {
            if ($f->isValid($rq->getParams())) {

                // Upload thumbnail and images
                $thumbnail = null;
                $images    = array();

                $uploader = new Apps_Plugin_Upload_File();
                $uploader->setSubCategory(Apps_Plugin_Upload_File::CAT_PRODUCT);
                $uploaded = $uploader->upload();

                // Resize images
                if($uploaded) {
                    $imageResize = new Apps_Plugin_ResizeImages();

                    foreach($uploaded as $key => $imageUploaded) {
                        if($key != 'thumbnail_link') {
                            $imageLink = $imageUploaded['uri'];
                            try {
                                $imageResize->load(PUBLIC_PATH . $imageLink);
                                $imageResize->resize(550, 550);
                                $imageResize->save(PUBLIC_PATH . $imageLink);
                            } catch (Exception $e) {
                                new Zend_Exception('Resize images error');
                            }
                            $images[] = $imageLink;
                        }
                    }

                    // Resize thumbnail
                    if(isset($uploaded['thumbnail_link'])) {
                        $thumbnail = $uploaded['thumbnail_link']['uri'];
                        try {
                            $imageResize->load(PUBLIC_PATH . $thumbnail);
                            $imageResize->resize(184, 220);
                            $imageResize->save(PUBLIC_PATH . $thumbnail);
                        } catch (Exception $e) {
                            new Zend_Exception('Resize thumbnail error');
                        }
                    }
                }

                $data = $f->getValues();
                $data['thumbnail_link'] = $thumbnail;

                // Parse to Json : Color, Size
                $data['color'] = Zend_Json::encode($f->getValue('product_color_id'));
                $data['size']  = Zend_Json::encode($f->getValue('product_size_id'));

                $keyFilters = array('images', 'product_color_id', 'product_size_id');

                // Insert data
                $pId = $tbProduct->safelyInsert($data, $keyFilters, true);

                if($pId) {
                    // Insert images product
                    $tbProductImage = new Model_DbTable_ProductImage();
                    if($images) {
                        foreach ($images as $key => $link) {
                            $tbProductImage->safelyInsert(array('product_id' => $pId, 'path' => $link, 'sorting_number' => $key));
                        }
                    }
                    $this->_flashMessenger->addMessage(self::$msgAddSuccess);
                } else {
                    // Unlink images
                    unlink(PUBLIC_PATH.$thumbnail);
                    if($images) {
                        foreach ($images as $value) {
                            unlink(PUBLIC_PATH . $value);
                        }
                    }
                    $this->_flashMessenger->addMessage(self::$msgAddFailed);
                }
                $this->_helper->redirector('read', null, null);
            }
        }
        $f->setLegend('Add New Product ');
        $this->view->form = $f;
    }

    public function updateAction() {
        $rq = $this->_request;
        $id = $rq->getParam('id');

        $tbProduct = new Model_DbTable_Product();

        if(!$id || !is_numeric($id) || !$tbProduct->fetchRow(array('id =?' => $id))) {
            $this->_helper->redirector('read', null, null);
        }

        $data = $tbProduct->fetchRow(array('id =?' => $id))->toArray();

        $f 	= new Admin_Form_AddProduct();
        $f->removeElement('images');

        if ($rq->isPost()) {
            if ($f->isValid($rq->getParams())) {

                // Upload thumbnail and images
                $thumbnail = $data['thumbnail_link'];

                $uploader = new Apps_Plugin_Upload_File();
                $uploader->setSubCategory(Apps_Plugin_Upload_File::CAT_PRODUCT);
                $uploaded = $uploader->upload();

                // Resize images
                if($uploaded) {
                    $imageResize = new Apps_Plugin_ResizeImages();

                    // Resize thumbnail
                    if(isset($uploaded['thumbnail_link'])) {
                        $thumbnail = $uploaded['thumbnail_link']['uri'];
                        try {
                            $imageResize->load(PUBLIC_PATH . $thumbnail);
                            $imageResize->resize(184, 220);
                            $imageResize->save(PUBLIC_PATH . $thumbnail);
                        } catch (Exception $e) {
                            new Zend_Exception('Resize thumbnail error');
                        }
                    }
                }

                $data = $f->getValues();
                $data['thumbnail_link'] = $thumbnail;

                // Parse to Json : Color, Size
                $data['color'] = Zend_Json::encode($f->getValue('product_color_id'));
                $data['size']  = Zend_Json::encode($f->getValue('product_size_id'));

                $keyFilters = array('product_color_id', 'product_size_id');

                $this->_flashMessenger->addMessage(
                        $tbProduct->safelyUpdate($data, array('id =?' => $id), $keyFilters, true)
                        ? self::$msgUpdateSuccess
                        : self::$msgUpdateFailed);

                $this->_helper->redirector('read', null, null);
            }
        }


        // Populate Form

        $pColor = Zend_Json::decode($data['color']);
        $pSize  = Zend_Json::decode($data['size']);

        $colorElement = $f->getElement('product_color_id');
        $sizeElement  = $f->getElement('product_size_id');

        $sizeElement->setValue($pSize);
        $colorElement->setValue($pColor);

        $f->populate($data);

        $f->setLegend('Update Product ');
        $this->view->form = $f;
    }

    //DELETE
    public function deleteAction() {
        $this->disableLayout(true, true);

        $id = $this->_getParam('id')
        ? $this->_getParam('id')
        : $this->_getParam('item_checker');

        if (!$id) {
            $this->_helper->redirector('read', null, null);
        }

        $tbProduct = new Model_DbTable_Product();
        if (is_array($id)) {
            foreach ($id as $k => $v) {
                if (is_numeric($v)) {
                    $tbProduct->update(array('status' => $tbProduct::STATUS_DELETED),
                            array('id =?'  => $v));
                }
            }
        } else if (is_numeric($id)) {
            if ($tbProduct->update(array('status' => $tbProduct::STATUS_DELETED),
                    array('id =?'  => $id)))
            {
                $this->_flashMessenger->addMessage(self::$msgDeleteSuccess);
            }
        }
        $this->_helper->redirector('read', null, null);
    }

    public function changeValueAction() {
        $this->disableLayout(true, true);
        $rq = $this->_request;
        $param  = $rq->getParam('p');
        $id 	= intval($rq->getParam('id'));
        $tbProduct = new Model_DbTable_Product();
        if(!($r = $tbProduct->fetchRow(array('id = ?' => $id))->toArray())) {
            echo '<script>window.location=window.location</script>
                    <a style="padding:10px 0;display:block;width:100%;text-align:center" href="'
                    . $this->getBacktrackUrl()
                    . '">Update Error (Record not found), please wait ...</a>';
        }

        switch ($param) {
            case 'isNew':
                ($r['is_new'] == Model_DbTable_Product::STATUS_ACTIVE)
                ? $tbProduct->safelyUpdate(array('is_new' 		=> Model_DbTable_Product::STATUS_INACTIVE),
                                           array('id =?'			=> $id))
                : $tbProduct->safelyUpdate(array('is_new' 		=> Model_DbTable_Product::STATUS_ACTIVE),
                                           array('id =?'			=> $id));
                break;

            case 'isSaleOff':
                ($r['is_sale_off'] == Model_DbTable_Product::STATUS_ACTIVE)
                ? $tbProduct->safelyUpdate(array('is_sale_off' 		=> Model_DbTable_Product::STATUS_INACTIVE),
                                           array('id =?'			=> $id))
                : $tbProduct->safelyUpdate(array('is_sale_off' 		=> Model_DbTable_Product::STATUS_ACTIVE),
                                           array('id =?'			=> $id));
                break;

            case 'isFeatured':
                ($r['is_featured'] == Model_DbTable_Product::STATUS_ACTIVE)
                ? $tbProduct->safelyUpdate(array('is_featured' 		=> Model_DbTable_Product::STATUS_INACTIVE),
                                           array('id =?'			=> $id))
                : $tbProduct->safelyUpdate(array('is_featured' 		=> Model_DbTable_Product::STATUS_ACTIVE),
                                           array('id =?'			=> $id));
                break;

            case 'isBestSelling':
                ($r['is_best_selling'] == Model_DbTable_Product::STATUS_ACTIVE)
                ? $tbProduct->safelyUpdate(array('is_best_selling' 		=> Model_DbTable_Product::STATUS_INACTIVE),
                                           array('id =?'			=> $id))
                : $tbProduct->safelyUpdate(array('is_best_selling' 		=> Model_DbTable_Product::STATUS_ACTIVE),
                                           array('id =?'			=> $id));
                break;

            case 'public':
                ($r['status'] == Model_DbTable_Product::STATUS_ACTIVE)
                ? $tbProduct->safelyUpdate(array('status'  => Model_DbTable_Product::STATUS_INACTIVE),
                                           array('id =?'	  => $id))
                : $tbProduct->safelyUpdate(array('status'  => Model_DbTable_Product::STATUS_ACTIVE),
                                           array('id =?'  => $id));
                break;

            default: break;
        }

        echo '<script>document.location.reload()</script>
                <a style="padding:10px 0;display:block;width:100%;text-align:center" href="'
                . $this->getBacktrackUrl()
                . '">Update successfully, please wait ...</a>';
    }
}